package com.itheima.controller;

import com.itheima.pojo.Result;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;
import java.util.StringJoiner;

@Slf4j
//代表全局异常处理器
@RestControllerAdvice
public class GlobalExceptionHandler {

    //处理异常
    @ExceptionHandler(value = Exception.class)
    public Result ex(Exception e) {//方法形参中指定能够处理的异常类型
        //记录异常的错误信息
     //   log.error("出现了异常:{}", e.getMessage());
      //  e.printStackTrace();//打印堆栈中的异常信息
        //捕获到异常之后，响应一个标准的Result
        log.error("捕获到异常，类型为: {}", e.getClass().getName());
        log.error("完整异常堆栈:", e);
        return Result.error("发生未知异常");
    }

/*    //重复key异常
    //DuplicateKeyException
    @ExceptionHandler(DuplicateKeyException.class)
    public Result ex(DuplicateKeyException e) {
        //获取最早出异常的  e.getCause();
        log.error("出现了异常:{}", e.getMessage());
        e.printStackTrace();
        if (e.getMessage().contains("Duplicate entry")) {
            String[] split = e.getMessage().split(" ");
            String msg = split[8] + "已存在";
            return Result.error(msg);
        }
        return Result.error("对不起,操作失败,请联系管理员");
    }*/
    @ExceptionHandler(DuplicateKeyException.class)
    public Result handleDuplicateKey(DuplicateKeyException e) {
        log.error("重复键异常: {}", e.getMessage());
        return Result.error("部门名称已存在");
    }

    //校验框架的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result ex(MethodArgumentNotValidException e) {
        //获取校验未通过的属性和错误信息
        List<FieldError> fieldErrors = e.getFieldErrors();
        //拼接器，以逗号进行拼接
        StringJoiner joiner = new StringJoiner(",");
        for (FieldError fieldError : fieldErrors) {
            //没通过校验的属性名
            String field = fieldError.getField();
            //没通过时自己写的提示信息message，@NotBland(message="")
            joiner.add(fieldError.getDefaultMessage());
            log.info(field + "：" + fieldError.getDefaultMessage());
        }

        return Result.error(joiner.toString());
    }

    //SignatureException,JWT signature does not match locally computed signature
    //ExpiredJwtException ,JWT expired at 2025-09-30T11:58:26Z
    //登录Jwt超时异常
    @ExceptionHandler(ExpiredJwtException.class)
    public Result ex(ExpiredJwtException e) {
        log.error("登录Jwt超时，请重新登录:{}", e.getMessage());
        e.printStackTrace();//打印堆栈中的异常信息
        return Result.error("登录超时，请重新登录");
    }
}